package com.mocha.common.core;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.mocha.common.kits.NumberKits;
import lombok.Getter;
import lombok.Setter;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: songkui
 * @date: 2022/3/10 16:56
 */
public class MochaHeader {

    public final static String HEADER_USERID = "User-id";
    public final static String HEADER_USERCODE = "User-code";
    public final static String HEADER_TOKEN = "Token";
    public final static String HEADER_AUTH = "Auth";

    private final static String ALL_HEADER = String.format("%s,%s,%s,%s", HEADER_USERID, HEADER_USERCODE, HEADER_TOKEN, HEADER_AUTH);

    public static String getUserCode(HttpServletRequest request){
        return null == request ? "" : request.getHeader(HEADER_USERCODE);
    }

    public static long getUserId(HttpServletRequest request){
        String userId = request.getHeader(HEADER_USERID);
        return NumberUtil.parseLong(userId);
    }

    public static UserInfo getUserInfo(HttpServletRequest request){
        String userCode = getUserCode(request);
        long userId = getUserId(request);
        if (NumberKits.isNotMinus(userId)){
            return new UserInfo(userCode, userId);
        }
        return null;
    }

    public static String getToken(HttpServletRequest request){
        return null == request ? "" : request.getHeader(HEADER_TOKEN);
    }

    public static String getAuth(HttpServletRequest request){
        return null == request ? "" : request.getHeader(HEADER_AUTH);
    }

    public static boolean isMochaHead(String name){
        if (StrUtil.isEmpty(name)){
            return false;
        }
        return ALL_HEADER.contains(name.trim()) ? true : false;
    }

    @Getter
    @Setter
    public static class UserInfo{
        private String userCode;
        private Long userId;
        public UserInfo(String userCode, Long userId){
            this.userCode = userCode;
            this.userId = userId;
        }
    }
}
